package com.qf.common.minio.utils;

import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * minio工具类
 */
@Component
public class MinioUtil {

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Autowired
    private MinioClient minioClient;

    /**
     * 判断bucket是否存在，不存在则创建
     */
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     *
     * @return
     */
    public String upload(InputStream inputStream, String fileName, String contentType) {

        // 如果桶不存在，直接创建
        existBucket(bucketName);

        try {

            // 上传到minio
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(inputStream, inputStream.available(), -1)
                    .contentType(contentType)
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        // 返回上传的文件名
        return endpoint + "/" + bucketName + "/" + fileName;
    }

    public String deleteFile(String filename) {

        try {
            // 删除文件
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucketName)
                    .object(filename)
                    .build());
            return "文件删除成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件删除失败：" + e.getMessage();
        }
    }


}
